<!-- AI模拟面试确认页面 -->
<template>
  <a-card class="interview-confirmation">
    <h1 class="title">面试通</h1>

    <a-divider />

    <a-form layout="vertical">
      <!-- 面试公司选择 -->
      <a-form-item label="面试公司">
        <a-select
          v-model:value="interviewInfo.companyId"
          :options="companyList"
          placeholder="请选择公司"
          style="width: 100%"
          allow-clear
          @change="handleCompanyChange"
        ></a-select>
      </a-form-item>

      <!-- 面试岗位选择 -->
      <a-form-item label="面试领域">
        <a-select
          v-model:value="interviewInfo.techFieldId"
          placeholder="请选择或输入岗位"
          :options="techFieldList"
          style="width: 100%"
          @change="handleTechFieldChange"
        ></a-select>
      </a-form-item>
      <a-form-item label="面试岗位">
        <a-select
          v-model:value="interviewInfo.positionId"
          placeholder="请选择或输入笔试的岗位"
          :options="positionList"
          style="width: 100%"
        ></a-select>
      </a-form-item>

      <!-- 面试模式选择 -->
      <a-form-item label="面试模式">
        <a-radio-group v-model:value="interviewInfo.languageMode" class="mode-options">
          <a-radio-button value="chinese">中文AI面试</a-radio-button>
          <a-radio-button value="english">English AI Interview</a-radio-button>
        </a-radio-group>
      </a-form-item>

      <!-- 面试简历选择 -->
      <a-form-item label="面试简历">
        <a-select
          v-model:value="interviewInfo.resumeId"
          placeholder="请选择面试的简历"
          :options="resumeList"
          style="width: 100%"
        >
          <template #option="{ label }">
            <span>📄 {{ label }}</span>
          </template>
        </a-select>
      </a-form-item>

      <!-- 选择面试官-->
      <a-form-item label="选择面试官">
        <a-select
          v-model:value="interviewInfo.interviewerId"
          placeholder="请选择面试官"
          style="width: 100%"
        >
          <a-select-option
            v-for="interviewer in interviewerList"
            :key="interviewer.value"
            :value="interviewer.value"
          >
            <div style="display: flex; align-items: center; gap: 8px">
              <a-image
                :src="interviewer.avatar"
                style="width: 40px; height: 30px; border-radius: 10%"
              />
              <span>{{ interviewer.label }}</span>
            </div>
          </a-select-option>
        </a-select>
      </a-form-item>

      <!-- 选择面试官类型 -->
      <a-form-item label="面试官类型">
        <a-select
          v-model:value="interviewInfo.interviewerType"
          placeholder="请选择面试官类型"
          :options="interviewerTypeList"
          style="width: 100%"
        ></a-select>
      </a-form-item>

      <!-- 系统检测状态 -->
      <a-form-item label="系统检测">
        <!-- 单独处理的麦克风检测 -->
        <div class="mic-check-container">
          <span class="status-icon"> 🎤 麦克风权限 </span>
          <div class="mic-actions">
            <a-tag :color="micStatus === 'ready' ? 'green' : 'orange'">
              {{ micStatus === 'ready' ? '已就绪' : '未检测' }}
            </a-tag>
            <a-button type="primary" size="small" @click="testMicrophone">测试麦克风</a-button>
          </div>
        </div>
        <!-- 摄像头检测 -->
        <div class="mic-check-container" style="margin-top: 12px">
          <span class="status-icon"> 📷 摄像头权限 </span>
          <div class="mic-actions">
            <a-tag :color="cameraStatus === 'ready' ? 'green' : 'orange'">
              {{ cameraStatus === 'ready' ? '已就绪' : '未检测' }}
            </a-tag>
            <a-button type="primary" size="small" @click="testCamera">测试摄像头</a-button>
          </div>
        </div>
        <a-list item-layout="horizontal" :data-source="systemChecks">
          <template #renderItem="{ item }">
            <a-list-item>
              <template #actions>
                <a-tag :color="item.status === 'ready' ? 'green' : 'orange'">
                  {{ item.status === 'ready' ? '已就绪' : '检测中...' }}
                </a-tag>
              </template>
              <a-list-item-meta>
                <template #title>
                  <span :class="`status-icon ${item.status}`">
                    {{ item.icon }} {{ item.name }}
                  </span>
                </template>
              </a-list-item-meta>
            </a-list-item>
          </template>
        </a-list>
      </a-form-item>

      <!-- 摄像头预览和照片确认区域 -->
      <div style="display: flex; gap: 16px; margin-top: 16px">
        <a-card v-if="cameraStatus === 'testing'" title="摄像头预览" style="flex: 1">
          <video
            ref="videoRef"
            autoplay
            playsinline
            style="width: 100%; height: 240px; border-radius: 8px"
          ></video>
          <canvas ref="canvasRef" style="display: none"></canvas>
          <div style="margin-top: 16px; text-align: center">
            <a-button type="primary" @click="takePhoto">拍照确认</a-button>
          </div>
        </a-card>

        <a-card v-if="photoData" title="照片确认" style="flex: 1" v-show="photoData">
          <img
            :src="photoData"
            style="width: 100%; height: 240px; object-fit: contain; border-radius: 8px"
          />
          <div style="margin-top: 16px; text-align: center">
            <a-button type="primary" style="margin-left: 8px" @click="retakePhoto"
              >重新拍照</a-button
            >
          </div>
        </a-card>
      </div>

      <a-divider />

      <!-- 开始按钮 -->
      <div class="actions">
        <a-button
          type="primary"
          size="large"
          :disabled="!canStartInterview"
          @click="startInterview"
        >
          开始技术面试
        </a-button>
      </div>
    </a-form>
  </a-card>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, nextTick } from 'vue'
import { removeLocalCache, setLocalCache } from '@/utils/LocalStorageUtils'
import {
  Card as ACard,
  Divider as ADivider,
  Form as AForm,
  FormItem as AFormItem,
  RadioGroup as ARadioGroup,
  RadioButton as ARadioButton,
  List as AList,
  ListItem as AListItem,
  ListItemMeta as AListItemMeta,
  Tag as ATag,
  Button as AButton,
  message,
} from 'ant-design-vue'
import { useLoadingPage } from '@/utils/LoadingHelper'
import { useRouter } from 'vue-router'
import {
  getCompanyListUsingGet, getPositionListUsingGet,
  getTechFieldAndPositionUsingGet,
  getTechFieldListUsingGet
} from '@/api/positionController'
import { getExtractedResumeUsingGet } from '@/api/resumeController'
import gsap from 'gsap'
import { saveInterviewTypeUsingGet } from '@/api/userController'
import { generateTecInterviewUsingPost } from '@/api/tecInterviewController'

const micStatus = ref('')
const cameraStatus = ref('')
const photoData = ref('')
const videoRef = ref(null)
const canvasRef = ref(null)
const router = useRouter()
const { withLoading } = useLoadingPage(router)

// 面试官
interface Interviewer {
  value: number;
  label: string;
  gender: string;
  avatar: string;
}

// 面试官列表
const interviewerList = ref<Interviewer[]>([
  {
    value: 1,
    label: '面试官1',
    gender: '男',
    avatar: 'https://zx-1343343346.cos.ap-chongqing.myqcloud.com/ai_interview/ai_interview_photo/interviewer1.png',
  },
  {
    value: 2,
    label: '面试官2',
    gender: '女',
    avatar: 'https://zx-1343343346.cos.ap-chongqing.myqcloud.com/ai_interview/ai_interview_photo/interviewer2.png',
  },
  {
    value: 3,
    label: '面试官3',
    gender: '男',
    avatar: 'https://zx-1343343346.cos.ap-chongqing.myqcloud.com/ai_interview/ai_interview_photo/interviewer3.png',
  },
  {
    value: 4,
    label: '面试官4',
    gender: '女',
    avatar: 'https://zx-1343343346.cos.ap-chongqing.myqcloud.com/ai_interview/ai_interview_photo/interviewer4.png',
  },
  {
    value: 5,
    label: '面试官5',
    gender: '女',
    avatar: 'https://zx-1343343346.cos.ap-chongqing.myqcloud.com/ai_interview/ai_interview_photo/interviewer5.png',
  },
  {
    value: 6,
    label: '面试官6',
    gender: '男',
    avatar: 'https://zx-1343343346.cos.ap-chongqing.myqcloud.com/ai_interview/ai_interview_photo/interviewer6.png',
  },
]);

// 面试信息
const interviewInfo = ref({
  companyId: '',
  techFieldId: '',
  positionId: '',
  resumeId: '',
  languageMode: 'chinese',
  interviewerType:'',
  //面试官序号
  interviewerId: ''
})
const systemChecks = ref([{ name: '网络连接', icon: '🌐', status: 'ready' }])

// 技术领域
const techFieldList = ref([])
// 面试岗位
const positionList = ref([])
//面试简历
const resumeList = ref([])
// 公司列表
const companyList = ref([])
// 面试官类型列表
const interviewerTypeList = ref([
  {
    value: '严肃型',
    label: '严肃型',
  },
  {
    value: '温柔型',
    label: '温柔型',
  }
])

//开始面试按钮是否可用
const canStartInterview = computed(() => {
  return (
    micStatus.value === 'ready' &&
    cameraStatus.value === 'ready' &&
    interviewInfo.value.positionId &&
    interviewInfo.value.resumeId &&
    interviewInfo.value.techFieldId &&
    (photoData.value || cameraStatus.value === 'ready')
  )
})

/**
 * 测试麦克风
 */
const testMicrophone = async () => {
  //提示正在测试麦克风
  message.info('正在测试麦克风，请稍候...')
  micStatus.value = 'testing'
  try {
    // 实际检测麦克风的代码
    const stream = await navigator.mediaDevices.getUserMedia({ audio: true })
    stream.getTracks().forEach((track) => track.stop())
    micStatus.value = 'ready'
    message.success('麦克风测试成功！')
  } catch (error) {
    micStatus.value = 'failed'
    message.error('麦克风访问被拒绝或不可用')
  }
}

/**
 * 测试摄像头
 */
const testCamera = async () => {
  message.info('正在请求摄像头权限，请稍候...')
  cameraStatus.value = 'testing'
  try {
    const stream = await navigator.mediaDevices.getUserMedia({ video: true })
    const video = videoRef.value
    if (video) {
      video.srcObject = stream
      video.onloadedmetadata = () => {
        video.play()
      }
    }
  } catch (error) {
    cameraStatus.value = 'failed'
    message.error('摄像头访问被拒绝或不可用')
  }
}

/**
 * 拍照
 */
const takePhoto = () => {
  const video = videoRef.value
  const canvas = canvasRef.value
  if (video && canvas) {
    canvas.width = video.videoWidth
    canvas.height = video.videoHeight
    const context = canvas.getContext('2d')
    context.drawImage(video, 0, 0, canvas.width, canvas.height)
    photoData.value = canvas.toDataURL('image/png')

    // 停止视频流
    const stream = video.srcObject
    if (stream) {
      stream.getTracks().forEach((track) => track.stop())
    }
    cameraStatus.value = 'ready'
  }
}

/**
 * 重新拍照
 */
const retakePhoto = () => {
  photoData.value = ''
  testCamera()
}

/**
 * 获取解析完成的简历
 * @param value
 */
const fetchExtractedResumeList = async () => {
  const data = await getExtractedResumeUsingGet()
  data.data.map((item) => {
    resumeList.value.push({ value: item.id, label: item.resumeName + '.pdf' })
  })
}

/**
 * 修改面试领域后的回调函数
 */
const handleTechFieldChange = async () => {
  positionList.value = []
  interviewInfo.value.positionId = ''
  // 获取岗位信息
  await fetchPositionList()
}
/**
 * 修改公司后的回调函数
 */
const handleCompanyChange = async () => {
  techFieldList.value = []
  positionList.value = []
  interviewInfo.value.techFieldId = ''
  interviewInfo.value.positionId = ''
  //获取技术领域列表
  await fetchTechFieldList()
}

/**
 * 获取公司列表
 */
const fetchCompanyList = async () => {
  const data = await getCompanyListUsingGet()
  data.data.map((item) => {
    companyList.value.push({ value: item.id, label: item.name })
  })
}

/**
 * 获取技术领域列表
 */
const fetchTechFieldList = async () => {
  const data = await getTechFieldListUsingGet()
  data.data.map((item) => {
    techFieldList.value.push({ value: item.id, label: item.name })
  })
}

/**
 * 根据公司id和技术领域id获取岗位列表
 */
const fetchPositionList = async () => {
  if(!interviewInfo.value.techFieldId || !interviewInfo.value.companyId) return
  const data = await getPositionListUsingGet({
    techFieldId: interviewInfo.value.techFieldId as any,
    companyId: interviewInfo.value.companyId as any,
  })
  data.data.map((item) => {
    positionList.value.push({ value: item.id, label: item.name })
  })
}

/**
 * 开始面试
 */
const startInterview = async () => {
  //将面试官id存储本地缓存中
  setLocalCache("interviewerId",  interviewInfo.value.interviewerId)
  //将面试官url存储本地缓存中
  setLocalCache("interviewerAvatar",  interviewerList.value[interviewInfo.value.interviewerId - 1].avatar)
  //将面试官性别存储到本地缓存中
  setLocalCache("interviewerGender",  interviewerList.value[interviewInfo.value.interviewerId - 1].gender)

  message.success(
    interviewInfo.value.languageMode === 'chinese' ? '开始技术面试' : 'Start Tec Interview'
  )
  // 存储用户面试类型 0-技术面，1-hr面
  await saveInterviewTypeUsingGet({
    type: 0,
  })

  // 跳转到加载页面
  await withLoading(
    //发送请求生成技术面记录
    () =>
      generateTecInterviewUsingPost({
        ...interviewInfo.value as any,
        //面试官性别
        interviewerGender: interviewerList.value[interviewInfo.value.interviewerId - 1].gender
      }),
    `/api/tec/interview/${interviewInfo.value.languageMode}`, // 操作完成后跳转回当前页面
    '/',
    'tec',
    false
  )
}

/**
 * 生命周期函数
 */
onMounted(() => {
  //清除面试官相关信息
  removeLocalCache('interviewerId')
  removeLocalCache('interviewerAvatar')
  removeLocalCache('interviewerGender')

  fetchCompanyList()
  fetchTechFieldList()
  fetchPositionList()

  fetchExtractedResumeList()
  nextTick(() => {
    gsap.from('.interview-confirmation', { opacity: 0, y: 40, duration: 1, ease: 'power3.out' })
    gsap.from('.title', {
      opacity: 0,
      scale: 0.9,
      duration: 0.8,
      delay: 0.2,
      ease: 'back.out(1.7)',
    })
    gsap.from('.mode-options', { opacity: 0, x: 20, duration: 0.7, delay: 0.3 })
    gsap.from('.mic-check-container', {
      opacity: 0,
      x: -20,
      duration: 0.7,
      delay: 0.4,
      stagger: 0.1,
    })
    gsap.from('.actions', { opacity: 0, y: 10, duration: 0.7, delay: 0.7 })
  })
})
</script>

<style scoped>
/* 调整卡片宽度 */
.ant-card {
  min-width: 50vw !important;
}

.mic-check-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 24px;
  border-bottom: 1px solid rgba(0, 0, 0, 0.06);
  margin-bottom: 8px;
  color: #1890ff;
  border-radius: 8px;
  background-color: rgba(24, 144, 255, 0.05);
}

.mic-actions {
  display: flex;
  align-items: center;
  gap: 8px;
}

.status-icon {
  font-size: 16px;
  margin-right: 8px;
}

.interview-confirmation {
  max-width: 800px;
  margin: 20px auto;
  padding: 24px;
  border-radius: 16px;
  background: rgba(255, 255, 255, 0.85);
  backdrop-filter: blur(10px);
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.08), 0 6px 12px rgba(24, 144, 255, 0.05);
  border: 1px solid rgba(255, 255, 255, 0.8);
  overflow: hidden;
  position: relative;
}

.interview-confirmation::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 6px;
  background: linear-gradient(135deg, rgba(24, 144, 255, 0.8), rgba(65, 117, 232, 0.8));
}

.title {
  text-align: center;
  margin-bottom: 0;
  font-size: 26px;
  font-weight: 700;
  background: linear-gradient(135deg, rgba(24, 144, 255, 1), rgba(65, 117, 232, 1));
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  letter-spacing: 1px;
}

:deep(.ant-divider) {
  margin: 24px 0;
  border-color: rgba(0, 0, 0, 0.06);
}

:deep(.ant-form-item-label) {
  font-weight: 500;
  color: #333;
}

:deep(.ant-select-selector) {
  border-radius: 8px !important;
  border: 1px solid rgba(0, 0, 0, 0.1) !important;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.02) !important;
  transition: all 0.3s ease !important;
  height: 40px !important;
}

:deep(.ant-select-selection-search) {
  height: 38px !important;
}

:deep(.ant-select-selection-item) {
  line-height: 38px !important;
}

:deep(.ant-select-selector:hover) {
  border-color: rgba(24, 144, 255, 0.4) !important;
}

:deep(.ant-select-focused .ant-select-selector) {
  border-color: rgba(24, 144, 255, 0.6) !important;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.1) !important;
}

.mode-options {
  width: 100%;
  display: flex;
}

.mode-options :deep(.ant-radio-button-wrapper) {
  flex: 1;
  text-align: center;
  height: 40px;
  line-height: 40px;
  border-color: rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.mode-options :deep(.ant-radio-button-wrapper:first-child) {
  border-radius: 8px 0 0 8px;
}

.mode-options :deep(.ant-radio-button-wrapper:last-child) {
  border-radius: 0 8px 8px 0;
}

.mode-options :deep(.ant-radio-button-wrapper-checked) {
  background: linear-gradient(135deg, rgba(24, 144, 255, 0.8), rgba(65, 117, 232, 0.8));
  border-color: transparent !important;
  color: white !important;
  box-shadow: none !important;
}

:deep(.ant-radio-button-wrapper-checked)::before {
  background-color: transparent !important;
}

:deep(.ant-list-item) {
  padding: 12px 16px;
  border-bottom: 1px dashed rgba(0, 0, 0, 0.05) !important;
  margin: 0;
  border-radius: 8px;
  transition: all 0.3s ease;
}

:deep(.ant-list-item:hover) {
  background-color: rgba(24, 144, 255, 0.03);
}

:deep(.ant-list-item:last-child) {
  border-bottom: none !important;
}

.status-icon.ready {
  color: #1890ff;
}

.confirmation-list :deep(.ant-checkbox-wrapper) {
  display: flex;
  align-items: flex-start;
  margin-bottom: 12px;
}

.actions {
  display: flex;
  justify-content: center;
  gap: 16px;
  margin-top: 24px;
}

:deep(.ant-btn-primary) {
  height: 44px;
  min-width: 160px;
  border-radius: 22px;
  font-size: 16px;
  font-weight: 500;
  background: linear-gradient(135deg, rgba(24, 144, 255, 0.9), rgba(65, 117, 232, 0.9));
  border: none;
  box-shadow: 0 4px 12px rgba(65, 117, 232, 0.2);
  transition: all 0.3s ease;
}

:deep(.ant-btn-primary:hover) {
  transform: translateY(-2px);
  box-shadow: 0 6px 16px rgba(65, 117, 232, 0.3);
  background: linear-gradient(135deg, rgb(24, 144, 255), rgb(65, 117, 232));
}

:deep(.ant-btn-primary:active) {
  transform: translateY(0);
}

:deep(.ant-tag) {
  border: none;
  border-radius: 4px;
  padding: 2px 8px;
  font-size: 12px;
  font-weight: 500;
}
</style>
